﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class CreateUICode : EditorWindow
{
    static private string rootPath = "Assets/Lua";
    GameObject source;
    string name;
    string path;
    int layer;

    [MenuItem("GameTools/Create UI Code")]
    public static void ConfigDialog()
    {
        EditorWindow.GetWindow(typeof(CreateUICode));
    }

    void OnGUI()
    {
        GUILayout.Label("页面选项", EditorStyles.boldLabel);
        source = (GameObject)EditorGUILayout.ObjectField("选定对象", source, typeof(GameObject));
        name = EditorGUILayout.TextField("脚本名称", name);
        path = EditorGUILayout.TextField("路径名称", path);
        layer = int.Parse(EditorGUILayout.TextField("UI层级", layer + ""));

        if (source != null)
        {
            if (GUILayout.Button("生成脚本"))
            {
                // 创建脚本根路径
                if (Directory.Exists(rootPath) == false)
                    Directory.CreateDirectory(rootPath);

                // 生成脚本
                CreateUIScript1(source, name, path, layer);
            }
        }
    }

    // 生成UI脚本
    static void CreateUIScript1(GameObject source, string name, string path, int layer)
    {
        // 创建脚本路径
        string realPath = $"{rootPath}/{path}";
        if (Directory.Exists(realPath) == false)
            Directory.CreateDirectory(realPath);
        if (Directory.Exists(realPath + "/Base") == false)
            Directory.CreateDirectory(realPath + "/Base");

        #region 生成UIView.lua脚本
        realPath = rootPath + "/" + path + "/Base/" + name + "View.lua.txt";

        if (File.Exists(realPath)) File.Delete(realPath);
        FileStream fs = new FileStream(realPath, FileMode.Create, FileAccess.ReadWrite);
        StreamWriter sw = new StreamWriter(fs);
        string str = "";
        string tName = name + "View";
        str += $"local {tName} = " + "{}\n" +
               $"setmetatable({tName}, " + "{ __index = UIBase})\n\n" +

               $"function {tName}:Create()\n" +
               $"\tself.name = \"{name}\"\n" +
               $"\tself.path = \"{path}\"\n" +
               "end\n\n";
        str += $"function {tName}:SetUIComponent(child)\n";
        bool i = true;
        List<string> buttonList = new List<string>();
        List<string> toggleList = new List<string>();
        Dictionary<string, string> notes = new Dictionary<string, string>();
        foreach (Transform child in source.GetComponentsInChildren<Transform>())
        {
            if (child.tag == "uiComponent")
            {
                if (i)
                {
                    str += $"\tif child.name == \"{child.name}\" then\n" +
                           $"\t\t{tName}.{child.name} = {ComponentMatching(child)}\n";
                    i = false;
                }
                else
                {
                    str += $"\telseif child.name == \"{child.name}\" then\n" +
                           $"\t\t{tName}.{child.name} = {ComponentMatching(child)}\n";
                }
                if (child.GetComponent<Button>() != null)
                {
                    buttonList.Add(child.name);
                    if (child.GetComponentInChildren<Text>() != null)
                        notes.Add(child.name, child.GetComponentInChildren<Text>().text);
                    else
                        notes.Add(child.name, "");
                }
                if (child.GetComponent<Toggle>() != null)
                {
                    toggleList.Add(child.name);
                    if (child.GetComponentInChildren<Text>() != null)
                        notes.Add(child.name, child.GetComponentInChildren<Text>().text);
                    else
                        notes.Add(child.name, "");
                }
            }
        }
        if (source.GetComponentsInChildren<Transform>().Length != 0) str += "\tend";
        str += "\nend\n\n";
        str += $"function {tName}:Init()\n";
        foreach (string s in buttonList)
        {
            str += $"\t{tName}.{s}.onClick:AddListener(function() self:ButtonClickHandler({tName}.{s}) end)\n";
        }
        foreach (string s in toggleList)
        {
            str += $"\t{tName}.{s}.onValueChanged:AddListener(function() self:ButtonClickHandler({tName}.{s}) end)\n";
        }
        if (buttonList.Count == 0) str += "\n";
        str += "end\n\n";
        str += $"return {tName}";
        sw.Write(str);
        sw.Flush();
        sw.Close();
        Debug.Log("生成脚本" + tName + ".lua.txt");
        #endregion

        #region 生成UI.lua脚本
        realPath = rootPath + "/" + path + "/" + name + ".lua.txt";
        if (File.Exists(realPath)) File.Delete(realPath);
        fs = new FileStream(realPath, FileMode.Create, FileAccess.ReadWrite);
        sw = new StreamWriter(fs);
        str = "";

        str += $"{name} = " + "{}\n" +
               $"local UITable = require(\"{path}/Base/{tName}\")\n\n" +

               $"function {name}.Create()\n" +
                "\tlocal ui = {}\n" +
                "\tsetmetatable(ui, {__index=UITable})\n" +
                "\tui:Create()\n" +
                $"\tui.layer = {layer}\n" +
                "\tUI.LoadUI(ui)\n" +
                "\treturn ui\n" +
                "end\n\n";
        str += "function UITable:Awake()\n" +
                "\tself:Init()\n" +
                "end\n\n";
        if (buttonList.Count != 0 || toggleList.Count != 0)
        {
            str += "function UITable:ButtonClickHandler(btn)\n";
            i = true;
            foreach (string s in buttonList)
            {
                if (i)
                {
                    str += $"\tif btn == self.{s} then -- {notes[s]}";
                    i = false;
                }
                else str += $"\telseif btn == self.{s} then -- {notes[s]}";

                if (s == "btn_close") str += " 关闭\n\t\tself:Close()\n";
                else str += "\n\t\t\n";
            }
            foreach (string s in toggleList)
            {
                if (i)
                {
                    str += $"\tif btn == self.{s} then -- {notes[s]}\n\t\t\n";
                    i = false;
                }
                else
                {
                    str += $"\telseif btn == self.{s} then -- {notes[s]}\n\t\t\n";
                }
            }
            str += "\tend\nend\n\n";
        }

        sw.Write(str);
        sw.Flush();
        sw.Close();
        Debug.Log("生成脚本" + name + ".lua.txt");
        #endregion
    }

    // 组件匹配
    static private string ComponentMatching(Transform go)
    {
        string str;
        if (go.GetComponent<Button>() != null) str = "Button";
        else if (go.GetComponent<Toggle>() != null) str = "Toggle";
        else if (go.GetComponent<Slider>() != null) str = "Slider";
        else if (go.GetComponent<InputField>() != null) str = "InputField";
        else if (go.GetComponent<Image>() != null) str = "Image";
        else if (go.GetComponent<Text>() != null) str = "Text";
        else str = "";

        return str == "" ? "child.gameObject" : $"child:GetComponent(\"{str}\")";
    }
}